package Group9.TodoManager.Actions;

import Group9.TodoManager.Controller.DateController;
import Group9.TodoManager.Data.Interface.ITableModel;
import Group9.TodoManager.Data.Date;
import Group9.TodoManager.Data.Task;
import Group9.TodoManager.DataStore.Repository;
import Group9.TodoManager.Settings;
import Group9.TodoManager.View.TaskUI;
import Group9.TodoManager.View.TodoManagerGUI;

import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.ImageIcon;

/**
 * This action is meant for adding a task create by a user in the repository.
 * @author Volkan Cambazoglu
 * @author Rupesh
 */
public class AddAction<T> extends TodoManagerAction {
    
	private Repository<Task> repository;
    private ITableModel<Task> tableModel;
    private TaskUI userInterface;

    /**
     * This creates an action for creating a task and adding it to the
     * repository
     * @param name The name of the action
     * @param icon The icon for the action
     * @param toolTipText The tool tip that should be displayed for the component
     * for which the action is associated.
     * @param tableModel The model that is shown in the table.
     * @param taskUI The UI used for capturing the user's information
     * @param repository The instance to communicate with the data store.
     */
    public AddAction(String name, ImageIcon icon, String toolTipText, 
                    /*int mnemonic,*/ ITableModel<Task> table, TaskUI taskUI,
                    Repository<Task> repo){
        super(name, icon);
        putValue(Action.SHORT_DESCRIPTION, toolTipText);
        //putValue(Action.MNEMONIC_KEY, mnemonic);
        userInterface = taskUI;
        repository = repo;
        tableModel = table;
    }

    /**
     * When this action is performed it will extract information about a task 
     * object from the UI it belongs to. According to the extracted information
     * either a new task will be created or an existing task will be edited. 
     * @param e event
     */
    @Override
    public void actionPerformed(ActionEvent e){
        /**
         * Text fields are retrieved from the user interface
         */
        String title = userInterface.getTitle();
        String priority = userInterface.getPriority();
        String category = userInterface.getCategory();
        String description = userInterface.getDescription();

        DateController dateController = new DateController();
        Date beginDate = dateController.extractDate(userInterface.getBeginDateUI());
        Date endDate = dateController.extractDate(userInterface.getEndDateUI());

        /**
         * If all of the fields are non-empty, then create a Task object and
         * add it to the repository of the application
         */
        if(!title.equals("")){
        	
        	if(priority == null){
        		priority = "";
        	}
        	if(category == null){
        		category = "";
        	}

        	if((DateController.compareDates(endDate, beginDate) != -1)){
	            Task task = null;
	
                TodoManagerGUI<T> mainUI = Settings.getMainGUI();
                
	            if(!userInterface.isEditting() &&
	               (DateController.compareDates(beginDate, new Date()) != -1)){
	            	// Create new task
		            task = new Task(beginDate, endDate, title, description,
	                           category, priority, Task.STRINGOFPENDING);
	
	                repository.addNewItem(task);
	                repository.Commit();
	
	                tableModel.addRow(task);
	                
	                updateList(task, mainUI, -1);
	                
	                userInterface.getJDialog().setVisible(false);
	
	                Settings.displayMessage(
	                		Settings.getCurrentResourceBundle().getString(
	                				"Message.TaskAdded"));
	            }
	            else if(!userInterface.isEditting()){
	            	Settings.displayMessage(
	            		Settings.getCurrentResourceBundle().getString(
	            				"Message.EarlyBeginDate"));
	            }
	            else if(userInterface.isEditting() &&
	 	               (DateController.compareDates(endDate, new Date()) != -1)){ 
	            	// Edit existing task
	                task = userInterface.getEdittedTask();
	                int indexInList = mainUI.getListUI().getListModel().indexOf(task);
	                
	                repository.removeItem(userInterface.getEdittedTask());
	                repository.Commit();
	                tableModel.removeRowAt(tableModel.getSelectedRowIndex());
	                                                
	                task.updateTask(beginDate, endDate, title, description,
	                                                    category, priority);
	
	                repository.addNewItem(task);
	                repository.Commit();
	                tableModel.addRow(task);
	                
	                updateList(task, mainUI, indexInList);
	                
	                userInterface.getJDialog().setVisible(false);
	
	                Settings.displayMessage(
	                	Settings.getCurrentResourceBundle().getString(
	                			"Message.TaskEdited"));
	            }
	            else{
	            	Settings.displayMessage(
	            		Settings.getCurrentResourceBundle().getString(
                			"Message.EarlyEndDate"));
	            }
        	}
        	else{
        		Settings.displayMessage(
    				Settings.getCurrentResourceBundle().getString(
                			"Message.EarlyEndBeginDate"));
        	}
        	Settings.getMainGUI().resetTxtarea();
        	Settings.getMainGUI().resetProgressModel();
        }
        else{
        	Settings.displayMessage(
    			Settings.getCurrentResourceBundle().getString(
                		"Message.AllFields"));
        }
    }
    
    /**
     * This method is for updating the list. The list is updated at both 
     * creation and editing of a task. task object might be applied to the list
     * according to the dates of it.
     * @param task the task object
     * @param mainUI main GUI of the application
     * @param index index of the task in the list. -1 if it is not on the list
     */
    private void updateList(Task task, TodoManagerGUI<T> mainUI, int index){
    	if(DateController.isSameDay(task.getBeginDate(), new Date()) ||
		   DateController.isSameDay(task.getEndDate(), new Date()) ||
		   (DateController.compareDates(task.getBeginDate(), new Date()) != 1 &&
		    DateController.compareDates(task.getEndDate(), new Date()) != -1)){
      				
             if(index != -1){
          		mainUI.editListElement(index, task);
          	 }
          	 else{
          		mainUI.addToList(task);
          	 }
      	}
    }
}
